package cn.bytecollege.user.filter;

import cn.bytecollege.common.constant.Resource;
import com.google.code.kaptcha.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "UserLoginFilter",servletNames = "UserLoginController")
public class UserLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        String msg = null;
        String method = req.getMethod();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String validCode = req.getParameter("validCode");
        if(method.equalsIgnoreCase("post")){
            if (username==null||username.equals("")){
                msg="请输入用户名";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher("/user/userLogin.jsp").forward(request,response);
                return;
            }
            if(password==null||password.equals("")){
                msg="请输入密码";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher("/user/userLogin.jsp").forward(request,response);
                return;
            }
            String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (validCode==null||validCode.equals("")||!validCode.equals(code)){
                msg = "请输入验证码";
                request.setAttribute("msg",msg);
                request.getRequestDispatcher("/user/userLogin.jsp").forward(request,response);
                return;
            }
            chain.doFilter(request,response);
            return;
        }
        chain.doFilter(request,response);
    }


}
